<template>
  <el-dialog
    v-model="dialogVisible"
    title="导出表头"
    width="800"
    :before-close="handleClose"
  >
    <el-checkbox-group v-model="checkList">
      <el-checkbox
        :value="item.key"
        v-for="(item, index) in titles"
        :key="index"
        :label="item.name"
      />
    </el-checkbox-group>

    <div style="margin-top: 20px">
      <el-input v-model="excelName" placeholder="文件导出名称" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="save" :loading="loading">
          确 认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();

let dialogVisible = ref(false);
let checkList = ref([]);
let loading = ref(false);
let params = ref({});
let excelName = ref("");
let selectList = ref([]); // 选中的列表

let titles = ref([
  { name: "报名时间", key: "_add_time" },
  { name: "课程名称", key: "course_info.name" },
  { name: "学员姓名", key: "user_detail_info.name" },
  { name: "联系方式", key: "user_detail_info.mobile" },
  { name: "身份证", key: "approvalContent.model.identityCard" },
  { name: "课程标签", key: "user_detail_info.tagList" },
  { name: "完成培训项目", key: "user_statistics_info.completedTrain" },
  { name: "培训完成率", key: "trainingCompleRate" },
  { name: "有效学时", key: "user_count_info.learningTime" },
  { name: "累计学时", key: "user_statistics_info.totalLearningTime" },
  { name: "考试分数", key: "examUsers_info" },
  { name: "考试合格", key: "user_count_info.passExam" },
  { name: "最后活跃时间", key: "user_statistics_info.lastActiveTime" },
  { name: "学员类型", key: "user_detail_info.role" },
  { name: "创建时间", key: "user_detail_info.addTime" },
  { name: "账号状态", key: "user_detail_info.disabled" },
]);

function handleClose() {
  excelName.value = "";
  checkList.value = [];
  selectList.value = [];
  params.value = {};
  dialogVisible.value = false;
}

function open(obj, selectArr) {
  return exportExcel(selectArr);
  params.value = { ...obj };
  selectList.value = proxy.$utils.deepcopy(selectArr);
  dialogVisible.value = true;
}

//导出数据
async function exportExcel(array) {
  let list = await setData(array); //未筛选
  downExcel(list, "课时记录");
}

async function setData(data) {
  let list = [];
  let bindMax = await proxy.$apis.trainList({ type: "bindIndexMax" });
  data.forEach((element) => {
    let first = {
      报名时间: proxy.$utils.dateTimeFormateFn(element._add_time, "all"),
      用户id: element.userId,
      课程名称: element.course_info.name,
      学员姓名: element.user_detail_info.name,
      联系方式: element.user_detail_info.mobile,
      身份证号: element.approvalContent.model.identityCard,
      课程标签: setTags(element).length,
    };
    let second = {};
    for (let index = 0; index < bindMax; index++) {
      second[`第${index + 1}天`] = tagStatus_format(element.tagsStatus, index);
    }
    let third = {
      培训完成状态: element.trainCompleted ? "已完成" : "未完成",
      学时: element.trainTotal * 8,
      公布学时: element.isMoXueYuanPublished
        ? element.isMoXueYuanPublished.currentTrainTotal * 8
        : "-",
      考试分数: score_format(element.examUsers_info),
      关联考试: score_format(element.examUsers_info, "total"),
      学时公布时间: element.isMoXueYuanPublished
        ? proxy.$utils.dateTimeFormateFn(element.isMoXueYuanPublished.nowTime)
        : "-",
      订单号: element.out_trade_no.toString(),
      最后活跃时间:
        element.user_statistics_info &&
        proxy.$utils.dateTimeFormateFn(
          element.user_statistics_info.lastActiveTime,
          "all"
        ),
      // 学员类型:
      //   element.user_detail_info.role == "admin" ? "管理员" : "普通成员",
      创建时间: proxy.$utils.dateTimeFormateFn(
        element.user_detail_info.addTime * 1000,
        "all"
      ),
      账号状态: element.user_detail_info.disabled == 0 ? "开启" : "关闭",
    };
    list.push({ ...first, ...second, ...third });
  });
  return list;
}

function setTags(item) {
  let tagList = item.user_detail_info.tagList;
  let tags = item.tags;
  let arr = [];
  tagList.forEach((element) => {
    if (tags.includes(element.id)) arr.push(element);
  });
  return arr;
}

/**
 * 根据指定键值对JSON数组去重
 * @param {Array} data - 待去重的JSON数组
 * @param {string} key1 - 第一个去重键
 * @param {string} key2 - 第二个去重键
 * @param {string} key3 - 第三个去重键
 * @returns {Array} - 去重后的新数组
 */
function uniqueByKeys(data, key1, key2, key3) {
  // 1. 创建Map存储唯一键组合[3,4](@ref)
  const keyMap = new Map();
  const result = [];

  // 2. 遍历原始数组
  for (const item of data) {
    // 3. 生成复合键（处理可能的undefined值）
    const compositeKey = `${item[key1] ?? ""}|${item[key2] ?? ""}|${
      item[key3] ?? ""
    }`;

    // 4. 检查是否重复
    if (!keyMap.has(compositeKey)) {
      // 5. 首次出现则存入结果和Map[2,6](@ref)
      keyMap.set(compositeKey, true);
      result.push({ ...item }); // 浅拷贝避免引用污染
    }
  }

  return result;
}

async function downExcel(arr, excelName) {
  let cols = []; //设置表头样式
  checkList.value.forEach((element) => {
    cols.push({ wch: 60 });
  });
  let query = {
    jsonData: arr,
    cols,
  };
  await proxy.$utils.exportToExcel(
    query,
    excelName ? excelName : "课时记录导出"
  );
}

function tagStatus_format(arr, index) {
  if (!arr) return;
  let current = index + 1;
  let sub = proxy.$utils.findIndexByField(arr, "index", current);
  if (sub != -1) return arr[sub].statusName || "-";
  return "-";
}

function format_fn(element, item) {
  let index = proxy.$utils.findIndexByField(titles.value, "name", item);
  let key = titles.value[index].key;

  if (key == "examUsers_info") {
    return score_format(element[key]);
  } else if (key == "user_detail_info.tagList") {
    let tags = getValueByPath(element, key);
    return tags.length;
  } else if (key == "user_detail_info.disabled") {
    return getValueByPath(element, key) == 0 ? "开启" : "关闭";
  } else if (key == "user_detail_info.role") {
    return element[key] == "admin" ? "管理员" : "普通成员";
  } else if (key == "_add_time") {
    return proxy.$utils.dateTimeFormateFn(element[key], "all");
  } else if (key == "user_detail_info.addTime") {
    return proxy.$utils.dateTimeFormateFn(
      getValueByPath(element, key) * 1000,
      "all"
    );
  } else if (key == "trainingCompleRate") {
    return trainingCompleRate(element) + "%";
    function trainingCompleRate(row) {
      let completedTrain = row.user_statistics_info.completedTrain || 0;
      let tagLength = row.user_detail_info.tagList.length || 0;
      return (completedTrain / tagLength) * 100;
    }
  } else {
    return getValueByPath(element, key);
  }

  function getValueByPath(obj, path) {
    const keys = path.split(".");
    let result = obj;
    for (let i = 0; i < keys.length; i++) {
      if (result === undefined) {
        return undefined; // 如果中途路径不存在，返回undefined
      }
      result = result[keys[i]];
    }
    return result; // 如果路径存在，返回最终的值
  }
}

function score_format(e, type?) {
  if (e && e.length) {
    let amount = 0;
    let arr = [];
    e.forEach((element) => {
      // if (element.stateValue == 2) {}
      arr.push(element);
      amount += Number(element.score);
    });
    if (type && type == "total") {
      return arr.length;
    } else {
      return amount ? (amount / arr.length).toFixed(2) : 0;
    }
  }
  return 0;
}

async function save() {
  // 获取 a 中的 name 值
  const aNames = [...titles.value].map((item) => item.name);
  // 根据 a 中的顺序对 b 进行排序
  const sortedB = [...checkList.value].sort((x, y) => {
    return aNames.indexOf(x) - aNames.indexOf(y);
  });
  try {
    loading.value = true;
    //如果有选中的值
    if (selectList.value.length) {
      let arr = [];
      selectList.value.forEach((element) => {
        let fieldObj = {};
        sortedB.forEach((item) => {
          fieldObj[item] = format_fn(element, item);
        });
        arr.push(fieldObj);
      });
      await downExcel(arr);
    } else {
      let { total } = await getInfo();
      let list = [];
      let totalPage = proxy.$utils.pageCount(total, params.value.pageSize);
      for (let index = 1; index <= totalPage; index++) {
        params.value.pageIndex = index;
        let { rows } = await getInfo();
        list.push(...rows);
      }
      let arr = [];

      list.forEach((element) => {
        let fieldObj = {};
        sortedB.forEach((item) => {
          fieldObj[item] = format_fn(element, item);
        });
        arr.push(fieldObj);
      });
      await downExcel(arr);
    }
    handleClose();
  } catch (error) {
    console.log("error", error);
  } finally {
    loading.value = false;
  }
}

async function getInfo() {
  try {
    loading.value = true;
    return await proxy.$apis.moxueyuanInfo({
      type: "list",
      data: params.value,
    });
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

defineExpose({ open });
</script>

<style lang="scss" scoped>
.el-table {
  margin-top: 25px;
}
</style>
